#!/usr/bin/perl
use strict;
use warnings;
use utf8;
binmode(STDOUT, ":utf8");

unless (defined($ARGV[0]))
{
  print_usage();
  exit(1);
}

use WWW::Mechanize;
use File::HomeDir;
use Term::ReadKey;

my $mech = WWW::Mechanize->new();
$mech->agent('Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0');

my $auth = read_auth_file();

my $host = '';
my $start_url = "http://$host/Login.asp";

my $action = $ARGV[0] || 'in';
my $comment = $ARGV[1] || '';
my $button = '';

if ($action eq 'out')
{
  $button = 'btnOUT';
}
else
{
  $button = 'btnIN';
}

my $url = $start_url;

printf "%s\n", "Fetching the login page: $url" ;
$mech->get($url);
die "Can't get the page $url: ", $mech->response->status_line unless $mech->success;

if ( $mech->content =~m/Kirjaudu si/ )
{
  printf "%s: %s\n", "Not logged in", "Will now login" ;

  unless (defined($auth->{'username'}) && defined($auth->{'password'}))
  {
    $auth = ask_for_auth($auth);
  }

  &login($mech, $auth);

  my $matchThis = 'Leimaus';
  if ( $mech->content =~m/$matchThis/ )
  {
    printf "%s: %s\n", "Response content includes text '$matchThis'", "Login was successful" ;
  }
  else
  {
    printf "%s: %s\n", "No '$matchThis' found!", "Login seems to have failed." ;
  }
}
else
{
  die "Unexpected error";
}

print "Filling out the form:\n";
# $button is set earlier

my %fields;

if ($comment eq 'ta')
{
  # työasia
  $fields{'PunchComment'} = '8';
}

$mech->form_name('RTPunch');
$mech->set_fields(%fields);
print "Submitting the form:\n";

# TODO: random coordinates x=1-65, y=1-28
$mech->click($button);
die "Form submission failed" unless ($mech->success);

##

print "Result page:\n";
print $mech->base() . "\n";
print $mech->content( format => 'text' );
exit;

# $mech->save_content( $0 . '.html' );

##

sub login
{
  # Timecon

  my $mech = shift;
  my $auth = shift;

  my %fields = (
    'user' => $auth->{'username'},
    'passwd' => $auth->{'password'},
  );

  $mech->form_name('login');
  $mech->set_fields(%fields);
  $mech->click();

  die "Form submission failed" unless ($mech->success);
}

sub ask_for_auth
{
  my $auth = shift;
   
  unless (defined($auth->{'username'}))
  {
    my $username;
    print "Username: ";
    $username = <STDIN>;
    chomp $username;
    print "Your username is: $username\n";
    $auth->{'username'} = $username;
  }

  unless (defined($auth->{'password'}))
  {
    my $password;
    print "Password (will not be displayed) : ";

    ReadMode('noecho');
    $password = ReadLine(0);
    ReadMode(0);

    chomp $password;
    print "Thanks for the password.\n";
    $auth->{'password'} = $password;
  }

  return $auth;
}

# not used
sub ask_for_it
{   
  my $question = shift || "Enter value, please";
  print "$question : ";
  my $answer = <STDIN>;
  chomp $answer;
  return $answer;
}

# not used
sub list_links
{
  my $mech = shift;

  my @links = $mech->find_all_links();

  foreach my $link (@links)
  {
    my $text = $link->text || '';
    my $url = $link->url;
    print "title: $text, url: $url\n";
  }
}

sub read_auth_file
{
  my $filePath = File::HomeDir->my_home . "/.authfile";

  if (!open(AUTHFILE, "<$filePath"))
  {
    warn "No auth file $filePath found: $!\n";
    return;
  }
  else
  {
    my $file_contents = do { local $/; <AUTHFILE> };
    my $auth = {};
    ($auth->{'username'}, $auth->{'password'}) = split(";", $file_contents);
    return $auth;
  }
}

sub print_usage
{
  print "Usage: $0 direction comment\n";
  print "  direction: in or out\n";
  print "  comment: accepted values: ta (työasia)\n\n";
  print "Auth file in your home directory should be named .authfile and \ncontain your userid and password separated by a ';'.\n";
}
